var _system = function () {
  this['version'] = Loader.c;
  this['root'] = Loader.s;
  this['sitename'] = Loader.p;
  this['renderTime'] = new Date();
  if (typeof window._user_ === 'object') {
    this['user'] = window._user_;
  }
  this.init();
};
_system.prototype = {
  /*
  系统初始化，目前只放入分享回掉函数
   */
  init: function () {
    (function ($) {
      $.extend({
        s: function (_s, _root) {
          return $('[data-selector="' + _s + '"]', _root || $('body'));
        },
        reverseChild : function(obj, child) {
          var childObj = $(obj).find(child).toArray();
          childObj.reverse();
          $(obj).html(childObj);
        }
      })
    })(jQuery);

    var _this = this;
    $(document).ajaxStart(function () {
      _this.message.loading.show();
    });
    $(document).ajaxStop(function () {
      _this.message.loading.hide();
    });
  },
  renderTpl: function (_tplname, _data, _callback) {
    return (typeof coreTpl != 'undefined') && coreTpl.get(_tplname, _data, _callback);
  },
  /*
  系统专属选择器
  @_selector 选择器名(data-selector)
  @_root 区块查找提高性能(默认为body体)
  system.s(selector) ||  system.s(selector,$(area));
   */
  s: function (_selector, _root) {
    return $('[data-selector="' + _selector + '"]', _root || $('body'));
  },
  /*
  判断当前浏览器是否支持某个css3属性
  @return boolean
  system.supportCss3Attr('transform');
   */
  supportCss3Attr: function (style) {
    var prefix = ['webkit', 'Moz', 'ms', 'o'],
      i,
      humpString = [],
      htmlStyle = document.documentElement.style,
      _toHumb = function (string) {
        return string.replace(/-(\w)/g, function ($0, $1) {
          return $1.toUpperCase();
        });
      };

    for (i in prefix) {
      humpString.push(_toHumb(prefix[i] + '-' + style));
    }
    humpString.push(_toHumb(style));
    for (i in humpString) {
      if (humpString[i] in htmlStyle) return true;
    }
    return false;
  },
  /*
  系统全局消息提示工具
   */
  message: {
    tipConfirm: function (_msg, _callback, _cancelback, _btns) {
      return top.dialog({
        okValue: (_btns && _btns[0]) || 'Sure',
        ok: _callback || function () {},
        cancelValue: (_btns && _btns[1]) || 'Cancel',
        cancel: _cancelback || function () {},
        content: '<div class="ui-dialog-custom"><div class="ui-dialog-icon"><i class="ud-icon ud-logo"></i></div>' + _msg + '</div>'
      }).showModal();
    },
    /*
    @confirm 提示确认框；_msg：消息文本||html；_callback：按钮1回掉；_cancelback：按钮2回掉；_btns：自定义按钮组合(默认['确定','取消']);
    system.message.confirm('hellow world',function(){console.log('ok')},function(){console.log('cancel')},['自定义按钮1','自定义按钮2'])；
     */
    confirm: function (_msg, _callback, _cancelback, _btns) {
      return top.dialog({
        okValue: (_btns && _btns[0]) || 'Sure',
        ok: _callback || function () {},
        cancelValue: (_btns && _btns[1]) || 'Cancel',
        cancel: _cancelback || function () {},
        content: '<div class="ui-dialog-custom"><div class="ui-dialog-icon"><i class="ud-icon ud-confirm"></i></div>' + _msg + '</div>'
      }).showModal();
    },
    tooltips: function (_dom, _config) {
      _default = {
        skin: 'ui-dialog-tips',
        quickClose: true
      }
      if (_config) {
        $.extend(_default, _config);
      }
      return top.dialog(_default).show(_dom);
    },
    prompt: function (_config) {
      if (typeof dialog != 'undefined') {
        var _default = {
          title: '请输入',
          okValue: 'Sure',
          ok: function () {
            var str = $(top.dialog.getCurrent().node).find(':text').val();
            top.dialog.getCurrent().remove();
            _config.callback && _config.callback.call(this, str);
          }
        }
        if (typeof (_config) != 'undefined') {
          $.extend(_default, _config);
        }
        _default['content'] = '<form onsubmit="return false;"><input type="text" value="" class="form-control" /></form>';
        return top.dialog(_default).showModal();
      }
    },
    /*
    @alert 普通提示框；_msg：消息文本||html；_callback：按钮回掉；_btns：自定义按钮(默认['确定']);
    system.message.alert('hellow world',function(){console.log('ok')},['自定义按钮'])；
     */
    alert: function (_msg, _callback, _btns) {
      return top.dialog({
        okValue: (_btns && _btns[0]) || 'Got it',
        ok: _callback || function () {},
        content: '<div class="ui-dialog-custom"><div class="ui-dialog-icon"><i class="ud-icon ud-success"></i></div>' + _msg + '</div>'
      }).showModal();
    },
    warning: function (_msg, _callback) {
      return top.dialog({
        okValue: 'Got it',
        ok: _callback || function () {},
        content: '<div class="ui-dialog-custom"><div class="ui-dialog-icon"><i class="ud-icon ud-warning"></i></div>' + _msg + '</div>'
      }).showModal();
    },
    success: function (_msg, _callback, _btns) {
      return top.dialog({
        okValue: 'Got it',
        ok: _callback || function () {},
        content: '<div class="ui-dialog-custom"><div class="ui-dialog-icon"><i class="ud-icon ud-success"></i></div>' + _msg + '</div>'
      }).showModal();
    },
    error: function (_msg, _callback) {
      return top.dialog({
        okValue: 'Got it',
        ok: _callback || function () {},
        content: '<div class="ui-dialog-custom"><div class="ui-dialog-icon"><i class="ud-icon ud-error"></i></div>' + _msg + '</div>'
      }).showModal();
    },

    close: function () {
      top.dialog.getCurrent().close();
    },

    reset: function () {
      top.dialog.getCurrent() && top.dialog.getCurrent().reset();
    },

    show: function (_config) {
      return top.dialog(_config).showModal();
    },
    /*
    轻量级消息提示，页面底部黑色块状提示
    joymain.message.light('hello');
     */
    _ligthTimer: null,
    light: function (msg, icon) {
      var _container = $('#ui-message-light'), _msgList = [];
      clearTimeout(this._ligthTimer);
      _container.removeClass('actived');
      this._ligthTimer = null;
      if (typeof icon != 'undefined') {
        _msgList.push('<img class="ui-message-light-icon" src="' + (Loader.s + Loader.p + 'images/icons/icon-ui-message-light-' + icon + '.png') + '" />');
      }
      _msgList.push(msg);
      if (_container.length) {
        $('.ui-message-light-content h5', _container).html(_msgList.join(''));
      } else {
        _container = $('<div/>', {'id': 'ui-message-light'}).html('<div class="ui-message-light-content"><h5>' + _msgList.join('') + '</h5></div>');
        _container.appendTo($('body'));
      }
      _container.addClass('actived');
      this._ligthTimer = setTimeout(function () {
        _container.removeAttr('class');
      }, 3000);
    },
    loading: {
      show: function () {
        var _container = $('#ui-message-loading', $(top.document.body));
        if (!_container.length) {
          _container = $('<div/>', {'id': 'ui-message-loading'});
          _container.appendTo($(top.document.body));
        }
        _container.addClass('actived');
      },
      hide: function () {
        top.$('#ui-message-loading').removeClass();
      }
    }
  },
  /*
  浏览器检测
   */
  browser: function () {
    var u = navigator.userAgent, app = navigator.appVersion;
    return {//移动终端浏览器版本信息
      trident: u.indexOf('Trident') > -1, //IE内核
      presto: u.indexOf('Presto') > -1, //opera内核
      webKit: u.indexOf('AppleWebKit') > -1,
      gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
      mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
      android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
      iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
      iPad: u.indexOf('iPad') > -1, //是否iPad
      webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
      weChat: u.toLowerCase().match(/MicroMessenger/i) == "micromessenger"
    };
  }(),
  renderTpl: function (_tplname, _data, _callback) {
    return (typeof coreTpl != 'undefined') && coreTpl.get(_tplname, _data, _callback);
  },
  back: function () {
    location.href = document.referrer;
  },
  ajax: function (_config) {
    var _this = this, config = {
      'url': '#',
      'type': 'get',
      'async': true,
      'cache': false,
      'dataType': 'json'
    }
    return $.ajax($.extend(false, config, _config));
  },
  localStorage: function () {
    return {
      set: function (_key, _val) {
        return window.localStorage ? localStorage.setItem(_key, _val) : core.Cookie.set(_key, _val, false, "/");
      },
      get: function (_key) {
        return window.localStorage ? localStorage.getItem(_key) : core.Cookie.get(_key);
      },
      del: function (_key) {
        return localStorage.removeItem(_key);
      }
    }
  }(),
  encodeHTML: function (str) {
    return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, "&quot;").replace(/'/g, "&#39;");
  },
  countDown: function (_config) {
    return (function (_config) {
      var config = {
        time: 40,
        callback: null,
        process: null,
        timeOut: null,
        timeStamp: new Date().getTime(),
        timer: null,
        clear: null
      }, _tempTime, _t;
      if (typeof (_config) == 'object') {
        config = $.extend(config, _config);
      }
      _tempTime = config['time'];
      config['timer'] = setInterval(function () {
        if (config['timer'] != null) {
          _tempTime--;
          if (_tempTime <= 0) {
            clearInterval(config['timer']);
            config['timer'] = null;
            config['callback'] && config['callback'].call(this);
          } else {
            _t = new Date().getTime();
            if (Math.round((_t - config['timeStamp']) / 1000) > config['time']) {
              clearInterval(config['timer']);
              config['timer'] = null;
              config['process'] && config['process'].call(this, 0, 100);
              config['timeOut'] && config['timeOut'].call(this);
              config['callback'] && config['callback'].call(this);
            } else {
              config['process'] && config['process'].call(this, _tempTime, 100 - (parseFloat(_tempTime / config['time']).toFixed(2) * 100));
            }
          }
        }
      }, 1000);
    })(_config);
  }
};
system = window.system = new _system();

